package com.example.myblog.controller;

import com.example.myblog.common.AjaxResult;
import com.example.myblog.common.ApplicationVariable;
import com.example.myblog.common.UserSessionTools;
import com.example.myblog.entity.UserInfo;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public AjaxResult reg(UserInfo userInfo){
        //保证UserInfo里面的字段和传过来的相同，即可直接利用对象接收传过来的
        //框架会将得到的自动转换成userInfo
        //1.非空判断
        if (userInfo == null||
        !StringUtils.hasLength(userInfo.getUsername())||
                !StringUtils.hasLength(userInfo.getPassword())
        )
        {
            return AjaxResult.fail(-1,"参数有误");
        }
        //2.调用UserService执行添加方法，将得到的结果加入到AjaxResult.data中
        int result=userService.reg(userInfo);
        return AjaxResult.success(result);
    }

    @RequestMapping("login")
    public AjaxResult login(String username, String password, HttpServletRequest request)
    {
        //1.非空判断
        if(!StringUtils.hasLength(username)||
                !StringUtils.hasLength(password)
        ){
            return AjaxResult.fail(-1,"参数有误");
        }
        //查找用户
        UserInfo userInfo=userService.login(username);
        if (userInfo == null||userInfo.getId()<0) {
            return AjaxResult.fail(-2,"用户名或密码输入错误");
        }
        //对比密码
        if(!password.equals(userInfo.getPassword()))
        {
            return AjaxResult.fail(-2,"用户名或密码输入错误");
        }
        //将当前登录成功的用户加入到session中
        HttpSession session=request.getSession();
        session.setAttribute(ApplicationVariable.SESSION_USERINFO_KEY,userInfo);

        return AjaxResult.success(1);

    }
    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        session.removeAttribute(ApplicationVariable.SESSION_USERINFO_KEY);

        return AjaxResult.success(1);
    }
    //判断当前用户是否登录
    @RequestMapping("/islogin")
    public AjaxResult islogin(HttpServletRequest request){
        if (UserSessionTools.getLoginUser(request)==null) {
            return AjaxResult.success(0);
        }
        return AjaxResult.success(1);
    }
}
